package com.dayuanit.mianshi;

import com.dayuanit.mianshi.game.Player;
import com.dayuanit.mianshi.game.PlayerManager;

import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.ConcurrentHashMap;

public class CommonPlayerManager implements PlayerManager {

    //key=用户名 vlaue=Player对象
    private static final Map<String, Player> playerMap = new ConcurrentHashMap<>(512);

    static {
        //启动定时器，每分钟检查是否有人掉线
        Timer timer = new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                CommonPlayerManager.task();
            }
        }, 0,3 * 1000);
    }

    private static void task() {
        playerMap.forEach((username, player) -> {
            if (player.isOffline()) {
                playerMap.remove(username);
            }
        });
    }

    @Override
    public void addPlayer(Player player) {
        playerMap.put(player.getUsername(), player);
    }

    @Override
    public Player getPlayer(String username) {
        return playerMap.get(username);
    }

    @Override
    public void broadcast(String message) {
        for (Map.Entry<String, Player> entry : playerMap.entrySet()) {
            entry.getValue().write(message);
        }

        playerMap.forEach((username, player) -> {
            if (player.isOffline()) {
               player.write(message);
            }
        });
    }
}
